<template>
  <div>
    <pro-table
      :columns="columns"
      :request="fetchTags"
      row-key="id"
      :pagination="false"
      :form-ref="setFormRef"
      :action-ref="setActionRef"
      :defaultFormData="{type:1}"
      @change="handleDetail"
      header-title=""
    >
      <template #option-render="{ dom }">
        <a-button type="primary" v-auth="'addTagBtn'" @click="handleAdd">添加</a-button>
        <component :is="dom[1]" />
        <component :is="dom[0]" />
      </template>
      <template #action="{ record }">
        <a-button type="text" @click="handleEdit(record)">编辑</a-button>
        <a-popconfirm content="确认删除么"  @ok="handleDelete(record.id)">
        <a-button  v-auth="'tagDelBtn'" status="danger" type="text">删除</a-button>
        </a-popconfirm>
      </template>
    </pro-table>
    <a-modal v-model:visible="detailVisible" title="标签详情">
      <p>{{ detail.name }}</p>
      <p>{{ detail.info }}</p>
      <p>{{ detail.status }}</p>
    </a-modal>
    <a-modal v-model:visible="formVisible" :title="formTitle">
      <a-form :model="formData" layout="vertical">
        <a-form-item label="名称">
          <a-input v-model="formData.name" />
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model="formData.info" />
        </a-form-item>
        <a-form-item label="类型">
          <a-select v-model="formData.type">
            <a-option :value="1">需求单类型</a-option>
            <a-option :value="2">需求单渠道</a-option>
            <a-option :value="3">用户标签</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model="formData.status">
            <a-option :value="0">正常</a-option>
            <a-option :value="1">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="父级标签">
          <a-tree-select v-model="formData.parentId" :data="parentTags"   :field-names="{ key: 'id', title: 'name' }" >
          </a-tree-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="formVisible = false">取消</a-button>
        <a-button type="primary" @click="handleSubmit">提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { Ref, defineComponent, ref, watch } from 'vue';
  import { getTagList, deleteTag, getTagDetail, saveTag } from '@/api/tag';
  import { isAuth } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';

  export default defineComponent({
    name: 'TagPage',
    setup() {
      const formRef = ref();
      const actionRef = ref();
      const setFormRef = (ref: Ref) => {
        formRef.value = ref;
        console.log(formRef.value.formRef
,'-form ref')
      };

      formRef.value?.formRef.onChange((changedValues: any, allValues: any) => {
       console.log('Form values changed:', changedValues, allValues);
    // 在这里处理表单变化
  });
      
      const setActionRef = (ref: Ref) => {
        actionRef.value = ref;
      };

      const columns = [
        { title: '编号', dataIndex: 'id', hideInSearch: true },
        { title: '名称', dataIndex: 'name', hideInSearch: true },
        { title: '描述', dataIndex: 'info', hideInSearch: true },
        { title: '是否使用', dataIndex: 'status', valueEnum: {
          0: { text: '启用', status: 'Success' },
          1: { text: '禁用', status: 'Default' },
        }, hideInSearch: true },
        
        { title: '类型', dataIndex: 'type', valueEnum: {
          1: { text: '需求单类型' },
          2: { text: '需求单渠道' },
          3: { text: '用户标签' },
        },
        
      },
        { title: '创建时间', dataIndex: 'createTime', hideInSearch: true },
        { title: '创建人', dataIndex: 'createUserName', hideInSearch: true },
        {
          title: '操作',
          dataIndex: 'action',
          slotName: 'action',
          width: 180,
          hideInSearch: true 
        },
      ];

      const pagination = ref({
        current: 1,
        pageSize: 10,
        total: 0,
      });

      const detail = ref({
        name: '',
        info: '',
        status: 1,
      });

      const detailVisible = ref(false);

      const formVisible = ref(false);
      const formTitle = ref('添加标签');
      const formData = ref({
        id: undefined,
        name: '',
        info: '',
        status: 0,
        parentId: 0,
        type: 1,
      });

      const parentTags = ref<Array<any>>([]);

      const fetchTags = async (params) => {
        console.log(params, 'params');
        const response = await getTagList(params);
        parentTags.value = [{id:0,name:'请选择父级'},...response.data] // 获取父级标签数据
        return {
          data: response.data, 
          success: true,
        };
      };

      const handleDelete = async (id: number) => {
       const res =  await deleteTag(id);
       debugger
       if(res.success){
        console.log(res,'res')
        // 删除成功后的操作
        actionRef.value.reload();
       }else{
        Message.error(res.message)
       }
       
      };

      const handleDetail = async (id: number) => {
        const response = await getTagDetail(id);
        detail.value = response.data;
        detailVisible.value = true;
      };

      const handleAdd = () => {
        formTitle.value = '添加标签';
        formData.value = {
          id: undefined,
          name: '',
          info: '',
          status: 0,
          type: 1,
          parentId: 0,
        };
        formVisible.value = true;
        actionRef.value.reload();
      };

      const handleEdit = (record: any) => {
        formTitle.value = '编辑标签';
        formData.value = { ...record };
        formVisible.value = true;
      };
      const  findNodeById =(tree, id)=> {
              for (const node of tree) {
                if (node.id === id) {
                  return node;
                }
                if (node.children) {
                  const result = findNodeById(node.children, id);
                  if (result) {
                    return result;
                  }
                }
              }
        return null;
      }

      const handleSubmit = async () => {
        const leve = 0;
        const parentId = formData.value.parentId;
       const parent = findNodeById(parentTags.value,parentId)
       console.log(parent)
       if(parent.level === 3) {
        Message.warning('三级分类不允许添加子分类');
        return
       }
        await saveTag(formData.value);
        formVisible.value = false;
        // 提交成功后的操作
        actionRef.value.reload();
      };

      return {
        columns,
        pagination,
        detail,
        detailVisible,
        formVisible,
        formTitle,
        formData,
        parentTags,
        fetchTags,
        handleDelete,
        handleDetail,
        handleAdd,
        handleEdit,
        handleSubmit,
        setFormRef,
        setActionRef,
      };
    },
  });
</script>